<!DOCTYPE html>
<html lang="zh-Hans">
<!--浏览器搞笑标题-->
<script type="text/javascript" src="/js/FunnyTitle.js"></script>
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Mono:300,300italic,400,400italic,700,700italic%7CMa+Shan+Zheng:300,300italic,400,400italic,700,700italic%7CKiwi+Maru:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"ec1ipse.gitee.io","root":"/","images":"/images","scheme":"Gemini","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta property="og:type" content="article">
<meta property="og:title" content="只要我坚持刷LeetCode，我就不是最菜的 @Linked List相关">
<meta property="og:url" content="https://ec1ipse.gitee.io/2021/06/04/blog020-leetcode-linked-list-golang/index.html">
<meta property="og:site_name" content="eclipse&#39;s blog">
<meta property="og:locale">
<meta property="og:image" content="https://gitee.com/ec1ipse/pics-storage/raw/master/img/20210604065623.png">
<meta property="og:image" content="https://gitee.com/ec1ipse/pics-storage/raw/master/img/20210604071056.png">
<meta property="og:image" content="https://gitee.com/ec1ipse/pics-storage/raw/master/img/20210604071313.png">
<meta property="og:image" content="https://gitee.com/ec1ipse/pics-storage/raw/master/img/20210604071812.png">
<meta property="article:published_time" content="2021-06-03T23:07:37.000Z">
<meta property="article:modified_time" content="2021-06-03T23:18:36.000Z">
<meta property="article:author" content="eclipse">
<meta property="article:tag" content="LeetCode">
<meta property="article:tag" content="Golang">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/ec1ipse/pics-storage/raw/master/img/20210604065623.png">


<link rel="canonical" href="https://ec1ipse.gitee.io/2021/06/04/blog020-leetcode-linked-list-golang/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-Hans'
  };
</script>
<title>只要我坚持刷LeetCode，我就不是最菜的 @Linked List相关 | eclipse's blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

  <!--浏览器搞笑标题-->
  <script type="text/javascript" src="/js/FunnyTitle.js"></script>
<link rel="alternate" href="/atom.xml" title="eclipse's blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">eclipse's blog</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">普通なんかごめんだ<br>僕は僕でいさせてくれ</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="Searching..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Reverse-Linked-List"><span class="nav-number">1.</span> <span class="nav-text">Reverse Linked List</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Recursive-Solution"><span class="nav-number">1.1.</span> <span class="nav-text">Recursive Solution</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Iterative-Solution"><span class="nav-number">1.2.</span> <span class="nav-text">Iterative Solution</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Reverse-Linked-List-II"><span class="nav-number">2.</span> <span class="nav-text">Reverse Linked List II</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Swap-Nodes-in-Pairs"><span class="nav-number">3.</span> <span class="nav-text">Swap Nodes in Pairs</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Recursive-Solution-1"><span class="nav-number">3.1.</span> <span class="nav-text">Recursive Solution</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Iterative-Solution-1"><span class="nav-number">3.2.</span> <span class="nav-text">Iterative Solution</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Linked-List-Cycle"><span class="nav-number">4.</span> <span class="nav-text">Linked List Cycle</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%93%88%E5%B8%8C%E8%A1%A8"><span class="nav-number">4.1.</span> <span class="nav-text">哈希表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BF%AB%E6%85%A2%E6%8C%87%E9%92%88"><span class="nav-number">4.2.</span> <span class="nav-text">快慢指针</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Linked-List-Cycle-II"><span class="nav-number">5.</span> <span class="nav-text">Linked List Cycle II</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%93%88%E5%B8%8C%E8%A1%A8-1"><span class="nav-number">5.1.</span> <span class="nav-text">哈希表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BF%AB%E6%85%A2%E6%8C%87%E9%92%88-1"><span class="nav-number">5.2.</span> <span class="nav-text">快慢指针</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%A6%E8%BE%9F%E8%B9%8A%E5%BE%84"><span class="nav-number">5.3.</span> <span class="nav-text">另辟蹊径</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="eclipse"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">eclipse</p>
  <div class="site-description" itemprop="description">时光和才华是相互转换的<br>我的一生就是拿时光去换取才华</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">25</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">15</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/eclipse-tenet" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;eclipse-tenet" rel="noopener" target="_blank">GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/ec1ipse" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;ec1ipse" rel="noopener" target="_blank">Gitee</a>
      </span>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://ec1ipse.gitee.io/2021/06/04/blog020-leetcode-linked-list-golang/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="eclipse">
      <meta itemprop="description" content="时光和才华是相互转换的<br>我的一生就是拿时光去换取才华">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="eclipse's blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          只要我坚持刷LeetCode，我就不是最菜的 @Linked List相关
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>
      

      <time title="Created: 2021-06-04 07:07:37 / Modified: 07:18:36" itemprop="dateCreated datePublished" datetime="2021-06-04T07:07:37+08:00">2021-06-04</time>
    </span>

  
      </div>
      <div class="post-meta">
    <span class="post-meta-item" title="Symbols count in article">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">Symbols count in article: </span>
      <span>4.3k</span>
    </span>
    <span class="post-meta-item" title="Reading time">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">Reading time &asymp;</span>
      <span>5 mins.</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <img align=center src="https://gitee.com/ec1ipse/pics-storage/raw/master/img/20210604065623.png" height="250" alt="LeetCode in Golang">

<span id="more"></span>

<h1 id="Reverse-Linked-List"><a href="#Reverse-Linked-List" class="headerlink" title="Reverse Linked List"></a>Reverse Linked List</h1><p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/reverse-linked-list/">https://leetcode-cn.com/problems/reverse-linked-list/</a></p>
<h2 id="Recursive-Solution"><a href="#Recursive-Solution" class="headerlink" title="Recursive Solution"></a>Recursive Solution</h2><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">reverseList</span><span class="token punctuation">(</span>head <span class="token operator">*</span>ListNode<span class="token punctuation">)</span> <span class="token operator">*</span>ListNode <span class="token punctuation">&#123;</span>
	<span class="token keyword">var</span> newHead <span class="token operator">*</span>ListNode
	<span class="token keyword">var</span> curr <span class="token operator">*</span>ListNode <span class="token operator">=</span> head

	<span class="token keyword">for</span> curr <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		next <span class="token operator">:=</span> curr<span class="token punctuation">.</span>Next
		curr<span class="token punctuation">.</span>Next <span class="token operator">=</span> newHead
		newHead <span class="token operator">=</span> curr
		curr <span class="token operator">=</span> next
	<span class="token punctuation">&#125;</span>

	<span class="token keyword">return</span> newHead
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="Iterative-Solution"><a href="#Iterative-Solution" class="headerlink" title="Iterative Solution"></a>Iterative Solution</h2><p>分解任务</p>
<p><img src="https://gitee.com/ec1ipse/pics-storage/raw/master/img/20210604071056.png" alt="image-20210604071055968"></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">reverseList</span><span class="token punctuation">(</span>head <span class="token operator">*</span>ListNode<span class="token punctuation">)</span> <span class="token operator">*</span>ListNode <span class="token punctuation">&#123;</span>
	<span class="token keyword">if</span> head <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token operator">||</span> head<span class="token punctuation">.</span>Next <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> head
	<span class="token punctuation">&#125;</span>

	newHead <span class="token operator">:=</span> <span class="token function">reverseList</span><span class="token punctuation">(</span>head<span class="token punctuation">.</span>Next<span class="token punctuation">)</span>
	head<span class="token punctuation">.</span>Next<span class="token punctuation">.</span>Next <span class="token operator">=</span> head
	head<span class="token punctuation">.</span>Next <span class="token operator">=</span> <span class="token boolean">nil</span>
	<span class="token keyword">return</span> newHead
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr>
<h1 id="Reverse-Linked-List-II"><a href="#Reverse-Linked-List-II" class="headerlink" title="Reverse Linked List II"></a>Reverse Linked List II</h1><p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/reverse-linked-list-ii/">https://leetcode-cn.com/problems/reverse-linked-list-ii/</a></p>
<p>整体思想是：（头插法）在需要反转的区间里，每遍历到一个节点，让这个新节点来到反转部分的起始位置。下面的图展示了整个流程。</p>
<p>链表问题一般可以在头指针之前再设置一个头指针，最后返回dummyNode.Next即可。</p>
<p><img src="https://gitee.com/ec1ipse/pics-storage/raw/master/img/20210604071313.png" alt="image-20210604071313375"></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">/**
 * Definition for singly-linked list.
 * type ListNode struct &#123;
 *     Val int
 *     Next *ListNode
 * &#125;
 */</span>
<span class="token keyword">func</span> <span class="token function">reverseBetween</span><span class="token punctuation">(</span>head <span class="token operator">*</span>ListNode<span class="token punctuation">,</span> left <span class="token builtin">int</span><span class="token punctuation">,</span> right <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token operator">*</span>ListNode <span class="token punctuation">&#123;</span>
    dummyNode <span class="token operator">:=</span> <span class="token operator">&amp;</span>ListNode<span class="token punctuation">&#123;</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">,</span> head<span class="token punctuation">&#125;</span>
    pre <span class="token operator">:=</span> dummyNode
    <span class="token comment">// Find the Node before left</span>
    <span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> left <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">&#123;</span>
        pre <span class="token operator">=</span> pre<span class="token punctuation">.</span>Next
    <span class="token punctuation">&#125;</span>

    curr <span class="token operator">:=</span> pre<span class="token punctuation">.</span>Next
    <span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> right <span class="token operator">-</span> left<span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">&#123;</span>
        next <span class="token operator">:=</span> curr<span class="token punctuation">.</span>Next
        curr<span class="token punctuation">.</span>Next <span class="token operator">=</span> next<span class="token punctuation">.</span>Next
        next<span class="token punctuation">.</span>Next <span class="token operator">=</span> pre<span class="token punctuation">.</span>Next
        pre<span class="token punctuation">.</span>Next <span class="token operator">=</span> next
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> dummyNode<span class="token punctuation">.</span>Next
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr>
<h1 id="Swap-Nodes-in-Pairs"><a href="#Swap-Nodes-in-Pairs" class="headerlink" title="Swap Nodes in Pairs"></a>Swap Nodes in Pairs</h1><p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/swap-nodes-in-pairs/">https://leetcode-cn.com/problems/swap-nodes-in-pairs/</a></p>
<h2 id="Recursive-Solution-1"><a href="#Recursive-Solution-1" class="headerlink" title="Recursive Solution"></a>Recursive Solution</h2><p>dummyNode助力写出更方便的代码</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">/**
 * Definition for singly-linked list.
 * type ListNode struct &#123;
 *     Val int
 *     Next *ListNode
 * &#125;
 */</span>
<span class="token keyword">func</span> <span class="token function">swapPairs</span><span class="token punctuation">(</span>head <span class="token operator">*</span>ListNode<span class="token punctuation">)</span> <span class="token operator">*</span>ListNode <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> head <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token operator">||</span> head<span class="token punctuation">.</span>Next <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> head
    <span class="token punctuation">&#125;</span>

    dummyNode <span class="token operator">:=</span> <span class="token operator">&amp;</span>ListNode<span class="token punctuation">&#123;</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">,</span> head<span class="token punctuation">&#125;</span>
    curr <span class="token operator">:=</span> dummyNode
    <span class="token keyword">for</span> curr <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token operator">&amp;&amp;</span> curr<span class="token punctuation">.</span>Next <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token operator">&amp;&amp;</span> curr<span class="token punctuation">.</span>Next<span class="token punctuation">.</span>Next <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        next <span class="token operator">:=</span> curr<span class="token punctuation">.</span>Next
        nnext <span class="token operator">:=</span> curr<span class="token punctuation">.</span>Next<span class="token punctuation">.</span>Next
        next<span class="token punctuation">.</span>Next <span class="token operator">=</span> nnext<span class="token punctuation">.</span>Next
        curr<span class="token punctuation">.</span>Next <span class="token operator">=</span> nnext
        nnext<span class="token punctuation">.</span>Next <span class="token operator">=</span> next
        curr <span class="token operator">=</span> curr<span class="token punctuation">.</span>Next<span class="token punctuation">.</span>Next
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> dummyNode<span class="token punctuation">.</span>Next
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">swapPairs</span><span class="token punctuation">(</span>head <span class="token operator">*</span>ListNode<span class="token punctuation">)</span> <span class="token operator">*</span>ListNode <span class="token punctuation">&#123;</span>
    dummyNode <span class="token operator">:=</span> <span class="token operator">&amp;</span>ListNode<span class="token punctuation">&#123;</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">,</span> head<span class="token punctuation">&#125;</span>
    curr <span class="token operator">:=</span> dummyNode
    <span class="token keyword">for</span> curr<span class="token punctuation">.</span>Next <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token operator">&amp;&amp;</span> curr<span class="token punctuation">.</span>Next<span class="token punctuation">.</span>Next <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        node1 <span class="token operator">:=</span> curr<span class="token punctuation">.</span>Next
        node2 <span class="token operator">:=</span> node1<span class="token punctuation">.</span>Next
        node1<span class="token punctuation">.</span>Next <span class="token operator">=</span> node2<span class="token punctuation">.</span>Next
        curr<span class="token punctuation">.</span>Next <span class="token operator">=</span> node2
        node2<span class="token punctuation">.</span>Next <span class="token operator">=</span> node1
        curr <span class="token operator">=</span> node1
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> dummyNode<span class="token punctuation">.</span>Next
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="Iterative-Solution-1"><a href="#Iterative-Solution-1" class="headerlink" title="Iterative Solution"></a>Iterative Solution</h2><p>递归问题核心关注的三点：</p>
<ol>
<li>返回值</li>
<li>调用单元做了什么</li>
<li>终止条件</li>
</ol>
<p>在本题中：</p>
<ol>
<li>返回值：交换完成的子链表</li>
<li>调用单元：设需要交换的两个结点为head next，head后连接后面交换完成的子链表，next连接head</li>
<li>终止条件：head为空或者next为空</li>
</ol>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">swapPairs</span><span class="token punctuation">(</span>head <span class="token operator">*</span>ListNode<span class="token punctuation">)</span> <span class="token operator">*</span>ListNode <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> head <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token operator">||</span> head<span class="token punctuation">.</span>Next <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> head
    <span class="token punctuation">&#125;</span>
    newHead <span class="token operator">:=</span> head<span class="token punctuation">.</span>Next
    head<span class="token punctuation">.</span>Next <span class="token operator">=</span> <span class="token function">swapPairs</span><span class="token punctuation">(</span>newHead<span class="token punctuation">.</span>Next<span class="token punctuation">)</span>
    newHead<span class="token punctuation">.</span>Next <span class="token operator">=</span> head
    <span class="token keyword">return</span> newHead
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr>
<h1 id="Linked-List-Cycle"><a href="#Linked-List-Cycle" class="headerlink" title="Linked List Cycle"></a>Linked List Cycle</h1><p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/linked-list-cycle/">https://leetcode-cn.com/problems/linked-list-cycle/</a></p>
<h2 id="哈希表"><a href="#哈希表" class="headerlink" title="哈希表"></a>哈希表</h2><p>最容易想到的方法是遍历所有节点，每次遍历到一个节点时，判断该节点此前是否被访问过。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">/**
 * Definition for singly-linked list.
 * type ListNode struct &#123;
 *     Val int
 *     Next *ListNode
 * &#125;
 */</span>
<span class="token keyword">func</span> <span class="token function">hasCycle</span><span class="token punctuation">(</span>head <span class="token operator">*</span>ListNode<span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">&#123;</span>
    visited <span class="token operator">:=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token keyword">map</span><span class="token punctuation">[</span><span class="token operator">*</span>ListNode<span class="token punctuation">]</span><span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token keyword">for</span> head <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token boolean">_</span><span class="token punctuation">,</span> ok <span class="token operator">:=</span> visited<span class="token punctuation">[</span>head<span class="token punctuation">]</span><span class="token punctuation">;</span> ok <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token boolean">true</span>
        <span class="token punctuation">&#125;</span>
        visited<span class="token punctuation">[</span>head<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
        head <span class="token operator">=</span> head<span class="token punctuation">.</span>Next
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> <span class="token boolean">false</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="快慢指针"><a href="#快慢指针" class="headerlink" title="快慢指针"></a>快慢指针</h2><p>定义两个指针，一快一满。慢指针每次只移动一步，而快指针每次移动两步。初始时，慢指针在位置 head，而快指针在位置 head.next。这样一来，如果在移动的过程中，快指针反过来追上慢指针，就说明该链表为环形链表。否则快指针将到达链表尾部，该链表不为环形链表。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">hasCycle</span><span class="token punctuation">(</span>head <span class="token operator">*</span>ListNode<span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> head <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token operator">||</span> head<span class="token punctuation">.</span>Next <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token boolean">false</span>
    <span class="token punctuation">&#125;</span>
    slow<span class="token punctuation">,</span> fast <span class="token operator">:=</span> head<span class="token punctuation">,</span> head<span class="token punctuation">.</span>Next
    <span class="token keyword">for</span> slow <span class="token operator">!=</span> fast <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> fast <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token operator">||</span> fast<span class="token punctuation">.</span>Next <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token boolean">false</span>
        <span class="token punctuation">&#125;</span>
        slow <span class="token operator">=</span> slow<span class="token punctuation">.</span>Next
        fast <span class="token operator">=</span> fast<span class="token punctuation">.</span>Next<span class="token punctuation">.</span>Next
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> <span class="token boolean">true</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr>
<h1 id="Linked-List-Cycle-II"><a href="#Linked-List-Cycle-II" class="headerlink" title="Linked List Cycle II"></a>Linked List Cycle II</h1><p><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/linked-list-cycle-ii/">https://leetcode-cn.com/problems/linked-list-cycle-ii/</a></p>
<h2 id="哈希表-1"><a href="#哈希表-1" class="headerlink" title="哈希表"></a>哈希表</h2><p>遍历链表中的每个节点，并将它记录下来；一旦遇到了此前遍历过的节点，就可以判定链表中存在环，并且把这个指向这个节点的指针返回。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">/**
 * Definition for singly-linked list.
 * type ListNode struct &#123;
 *     Val int
 *     Next *ListNode
 * &#125;
 */</span>
<span class="token keyword">func</span> <span class="token function">detectCycle</span><span class="token punctuation">(</span>head <span class="token operator">*</span>ListNode<span class="token punctuation">)</span> <span class="token operator">*</span>ListNode <span class="token punctuation">&#123;</span>
    visited <span class="token operator">:=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token keyword">map</span><span class="token punctuation">[</span><span class="token operator">*</span>ListNode<span class="token punctuation">]</span><span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token keyword">for</span> head <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token boolean">_</span><span class="token punctuation">,</span> ok <span class="token operator">:=</span> visited<span class="token punctuation">[</span>head<span class="token punctuation">]</span><span class="token punctuation">;</span> ok <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> head
        <span class="token punctuation">&#125;</span>
        visited<span class="token punctuation">[</span>head<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
        head <span class="token operator">=</span> head<span class="token punctuation">.</span>Next
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="快慢指针-1"><a href="#快慢指针-1" class="headerlink" title="快慢指针"></a>快慢指针</h2><p>重点： 注意数学推导</p>
<p><img src="https://gitee.com/ec1ipse/pics-storage/raw/master/img/20210604071812.png" alt="image-20210604071812496"></p>
<pre class="line-numbers language-none"><code class="language-none">关于快慢指针移动长度的推导：
[疑惑点：慢指针不会在环中跑满一圈]
fast &#x3D; a + (b+c)*n + b
slow &#x3D; a + b
fast &#x3D; 2*slow
&#x3D;&#x3D;&gt; a &#x3D; c + (n-1)*(b+c)
&#x3D;&#x3D;&gt; 从相遇点到入环点的距离加上 n-1n−1 圈的环长，恰好等于从链表头部到入环点的距离
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">detectCycle</span><span class="token punctuation">(</span>head <span class="token operator">*</span>ListNode<span class="token punctuation">)</span> <span class="token operator">*</span>ListNode <span class="token punctuation">&#123;</span>
    slow<span class="token punctuation">,</span> fast <span class="token operator">:=</span> head<span class="token punctuation">,</span> head
    <span class="token keyword">for</span> fast <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        slow <span class="token operator">=</span> slow<span class="token punctuation">.</span>Next
        <span class="token keyword">if</span> fast<span class="token punctuation">.</span>Next <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token boolean">nil</span>
        <span class="token punctuation">&#125;</span>
        fast <span class="token operator">=</span> fast<span class="token punctuation">.</span>Next<span class="token punctuation">.</span>Next
        <span class="token keyword">if</span> slow <span class="token operator">==</span> fast <span class="token punctuation">&#123;</span>
            p <span class="token operator">:=</span> head
            <span class="token keyword">for</span> p <span class="token operator">!=</span> slow <span class="token punctuation">&#123;</span>
                p <span class="token operator">=</span> p<span class="token punctuation">.</span>Next
                slow <span class="token operator">=</span> slow<span class="token punctuation">.</span>Next
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">return</span> p
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="另辟蹊径"><a href="#另辟蹊径" class="headerlink" title="另辟蹊径"></a>另辟蹊径</h2><p>说明：不允许修改给定的链表。【如果这个条件不存在的话，另一种解法】</p>
<p>思路：new一个结点temp ， 用一个指针从链表头开始遍历,每次都让链表的next指向temp，这样链表就被拆开了，如果没有环就结束到NULL，如果有环那么必然在遇到入口时，入口的next已经在之前被指向了temp，判断是否next=temp如果相等，那么这个点就是入口</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">detectCycle</span><span class="token punctuation">(</span>head <span class="token operator">*</span>ListNode<span class="token punctuation">)</span> <span class="token operator">*</span>ListNode <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> head <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token boolean">nil</span>
    <span class="token punctuation">&#125;</span>
    curr <span class="token operator">:=</span> head
    temp <span class="token operator">:=</span> <span class="token operator">&amp;</span>ListNode<span class="token punctuation">&#123;</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">&#125;</span>
    <span class="token keyword">for</span> curr <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> curr<span class="token punctuation">.</span>Next <span class="token operator">==</span> temp <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> curr
        <span class="token punctuation">&#125;</span>
        p <span class="token operator">:=</span> curr<span class="token punctuation">.</span>Next
        curr<span class="token punctuation">.</span>Next <span class="token operator">=</span> temp
        curr <span class="token operator">=</span> p
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>Post author:  </strong>eclipse
  </li>
  <li class="post-copyright-link">
      <strong>Post link: </strong>
      <a href="https://ec1ipse.gitee.io/2021/06/04/blog020-leetcode-linked-list-golang/" title="只要我坚持刷LeetCode，我就不是最菜的 @Linked List相关">https://ec1ipse.gitee.io/2021/06/04/blog020-leetcode-linked-list-golang/</a>
  </li>
  <li class="post-copyright-license">
    <strong>Copyright Notice:  </strong>All articles in this blog are licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-Hans" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> unless stating additionally.
  </li>
</ul>
</div>

          <div class="followme">
  <span>Welcome to my other publishing channels</span>

  <div class="social-list">

      <div class="social-item">
        <a target="_blank" class="social-link" href="/atom.xml">
          <span class="icon">
            <i class="fa fa-rss"></i>
          </span>

          <span class="label">RSS</span>
        </a>
      </div>
  </div>
</div>

          <div class="post-tags">
              <a href="/tags/LeetCode/" rel="tag"><i class="fa fa-tag"></i> LeetCode</a>
              <a href="/tags/Golang/" rel="tag"><i class="fa fa-tag"></i> Golang</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/05/21/blog019-port-fixing/" rel="prev" title="命令行下查看端口占用情况">
                  <i class="fa fa-chevron-left"></i> 命令行下查看端口占用情况
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/06/07/blog021-golang-multiparameters/" rel="next" title="Golang中的可变参数">
                  Golang中的可变参数 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2021 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">eclipse</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="Symbols count total">29k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="Reading time total">30 mins.</span>
  </span>
</div>

    </div>
  </footer>

  
  <script size="300" alpha="0.6" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>





  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>

  





<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"left","width":150,"height":300},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
